import json
import requests
from dashscope import Generation

# 1. 定义天气查询函数的schema
weather_query_schema = {
    "name": "get_weather", # name 指定函数名称
    "description": "获取指定城市的天气信息",
     # parameters 定义函数的入参格式
    "parameters": { 
        "type": "object",
        "properties": {
            "city": {
                "type": "string",
                "description": "城市名称，如北京、上海等"
            },
            "date": {
                "type": "string",
                "description": "查询日期，如今天、明天等，默认为今天"
            }
        },
        "required": ["city"]
    },
    # returns 定义函数的返回格式
    "returns": {
        "type": "object",
        "properties": {
            "temperature": {
                "type": "string",
                "description": "温度，如25℃"
            },
            "weather": {
                "type": "string",
                "description": "天气状况，如晴、多云、雨等"
            },
            "humidity": {
                "type": "string",
                "description": "湿度，如80%"
            },
            "wind": {
                "type": "string",
                "description": "风力，如3级"
            }
        }
    }
}

# 2. 模拟天气查询函数的实现
def get_weather(city, date="今天"):
    """获取指定城市的天气信息，调用和风天气API"""
    # 和风天气API配置
    api_key = "6aa58b7fb6474923914007e10308685a"  # 重要：使用前请替换为你在和风天气开发平台申请的API密钥
    # 获取API密钥：注册和风天气开发平台账号 -> 创建应用 -> 获取API Key
    api_url_base = "https://mg6r6v3ckc.re.qweatherapi.com"
    api_url_geo = "/geo/v2/city/lookup" # 城市名称经纬度坐标
    api_url_now = "/v7/weather/now" # 实时天气

    # 获取城市的 id 信息
    city_id = ""
    try:
        geoparams = {
            "location": city
        }
        geoheaders = {
            "X-QW-Api-Key": api_key
        }
        response = requests.get(api_url_base+api_url_geo, params=geoparams,headers=geoheaders)
        georesult = response.json()
        if georesult.get("code") == "200":
            location = georesult.get("location", [{}])[0]
            locationid = location.get("id")
            print(f"区域id为: {locationid}")
            city_id = locationid
        else:
            print(f"API返回错误，状态码: {georesult.get('code')}")

    except requests.exceptions.RequestException as e:
                print(f"请求和风天气API出错: {str(e)}")
                return {"temperature": "未知", "weather": "未知", "humidity": "未知", "wind": "未知"}
    except Exception as e:
                print(f"处理天气数据出错: {str(e)}")
                return {"temperature": "未知", "weather": "未知", "humidity": "未知", "wind": "未知"}
    # 根据城市id 获取天气信息
    try:
        # 构建请求参数
        params = {
            "location": city_id,  # 和风天气API支持直接使用城市名称
            "lang": "zh"  # 返回结果的语言，中文
        }
        # 发送API请求
        # requests 添加header 信息
        headers = {
            "X-QW-Api-Key": api_key
        }
        print(f"Request Params: {params}")
        response = requests.get(api_url_base+api_url_now, params=params,headers=headers)
        response.raise_for_status()  # 检查请求是否成功
        # 解析返回的JSON数据
        data = response.json()
        # 检查API返回状态码
        if data.get("code") == "200":
            # 提取天气数据
            weather_now = data.get("now", {})
            
            # 构建返回结果，格式与schema一致
            result = {
                "temperature": f"{weather_now.get('temp', '未知')}℃",
                "weather": weather_now.get("text", "未知"),
                "humidity": f"{weather_now.get('humidity', '未知')}%",
                "wind": f"{weather_now.get('windScale', '未知')}级"
            }
            return result
        else:
            print(f"API返回错误，状态码: {data.get('code')}")
            return {"temperature": "未知", "weather": "未知", "humidity": "未知", "wind": "未知"}
            
    except requests.exceptions.RequestException as e:
        print(f"请求和风天气API出错: {str(e)}")
        return {"temperature": "未知", "weather": "未知", "humidity": "未知", "wind": "未知"}
    except Exception as e:
        print(f"处理天气数据出错: {str(e)}")
        return {"temperature": "未知", "weather": "未知", "humidity": "未知", "wind": "未知"}

# 3. 定义函数工具列表
function_tools = [
    {
        "type": "function",
        "function": weather_query_schema # 函数工具的schema
    }
]

# 4. 函数调用处理器
def function_call_handler(function_call):
    """处理模型返回的函数调用请求"""
    function_name = function_call.get('name')
    arguments = json.loads(function_call.get('arguments', '{}'))
    
    if function_name == 'get_weather':
        city = arguments.get('city')
        date = arguments.get('date', '今天')
        return get_weather(city, date)
    else:
        return {"error": f"未知函数: {function_name}"}

# 运行示例
if __name__ == "__main__":
    main()